package com.example.goodpet.activity.Fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.example.goodpet.R;
import com.example.goodpet.activity.adapter.ResultTieziRecycleViewAdapter;
import com.example.goodpet.activity.adapter.ResultUserRecycleViewAdapter;
import com.example.goodpet.base.BaseFragment;
import com.example.goodpet.base.BaseFragmentForView;
import com.example.goodpet.bean.ResponseBody;
import com.example.goodpet.bean.User;
import com.example.goodpet.common.EndlessRecyclerOnScrollListener;
import com.example.goodpet.common.LoadMoreWrapper;
import com.example.goodpet.common.LoadingPage;
import com.example.goodpet.community.bean.UserTieziInfo;
import com.example.goodpet.home.fragment.HomeFragment;
import com.example.goodpet.service.HomeService;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.TimeSeed;

import java.util.LinkedList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


public class SearchResultOfCommunityFragment extends BaseFragmentForView {
    private static final String TAG = HomeFragment.class.getSimpleName();

    private RecyclerView rv_search_result_user;

    private Retrofit retrofit;
    private HomeService homeService;

    private List<UserTieziInfo> userTieziInfos;

    //    用来获取布局
    private LayoutInflater mLayoutInflater;
    private List<DelegateAdapter.Adapter> subAdapters = new LinkedList();
    //    VLayout
    private VirtualLayoutManager layoutManager;

    private String searchContent;
    private long seed= TimeSeed.Get();


    @Override
    protected void LoadPage() {
        homeService.selectTieziBySearch(seed,searchContent,1, MyApplication.user.getId())
                .enqueue(new Callback<ResponseBody<List<UserTieziInfo>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<UserTieziInfo>>> call, Response<ResponseBody<List<UserTieziInfo>>> response) {
                        ResponseBody<List<UserTieziInfo>> body = response.body();
                        if (body.getCode() == 200) {
                            loadingPage.setStateCurrent(LoadingPage.STATE_SUCCESS);
                            loadingPage.setStateCurrent(LoadingPage.STATE_SUCCESS);
                            userTieziInfos = body.getData();
                        } else {
                            loadingPage.setStateCurrent(LoadingPage.STATE_EMPTY);
                            loadingPage.setStateCurrent(LoadingPage.STATE_EMPTY);
                            userTieziInfos = null;
                            //UIUtils.toast("未获取到响应数据", false);
                        }
                        initVLayoutRvUser();
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<UserTieziInfo>>> call, Throwable t) {
//                            Log.e(TAG, "onFailure: "+t.getMessage() );
                        //UIUtils.toast("通信失败",false);
                        loadingPage.setStateCurrent(LoadingPage.STATE_ERROR);
                    }
                });
    }

    @Override
    protected void initData() {
        searchContent=getArguments().getString("searchContent");
        retrofit= RetrofitSingleton.getRetrofitConstance();
        homeService=retrofit.create(HomeService.class);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_search_result_of_user;
    }

    @Override
    public void initListener() {
        super.initListener();
    }

    @Override
    protected void initView(View inflate) {
        super.initView(inflate);
        rv_search_result_user=inflate.findViewById(R.id.rv_search_result_user);
    }

    private void initVLayoutRvUser() {
        //1.设置总布局管理器
        layoutManager = new VirtualLayoutManager(mContext);
        rv_search_result_user.setLayoutManager(layoutManager);
        //2.设置回收池大小（相同类型的View可以复用，防止多次创建ItemView）
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 10);
        rv_search_result_user.setRecycledViewPool(viewPool);
        //3.逐个设置子模块适配器
        subAdapters.clear();
        addUserAdapter();

        //4.设置总适配器
        DelegateAdapter mainAdapter = new DelegateAdapter(layoutManager, true);
        mainAdapter.setAdapters(subAdapters);
        rv_search_result_user.setAdapter(mainAdapter);
    }

    private void addUserAdapter() {
        GridLayoutHelper layoutHelper = new GridLayoutHelper(2);
        ResultTieziRecycleViewAdapter adapter = new ResultTieziRecycleViewAdapter(mContext, userTieziInfos);
        LoadMoreWrapper loadMoreWrapper = new LoadMoreWrapper(adapter){
            @Override
            public LayoutHelper onCreateLayoutHelper() {
                return layoutHelper;
            }
        };
        subAdapters.add(loadMoreWrapper);

        rv_search_result_user.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING);
                homeService.selectTieziBySearch(seed,searchContent  , ++loadMoreWrapper.page,MyApplication.user.getId())
                        .enqueue(new Callback<ResponseBody<List<UserTieziInfo>>>() {
                            @Override
                            public void onResponse(Call<ResponseBody<List<UserTieziInfo>>> call, Response<ResponseBody<List<UserTieziInfo>>> response) {
                                ResponseBody<List<UserTieziInfo>> body = response.body();
                                if(body.getCode()==200){
                                    List<UserTieziInfo> data = body.getData();
                                    userTieziInfos.addAll(data);
                                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_COMPLETE);
                                }else if(body.getCode()==404){
                                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_END);
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody<List<UserTieziInfo>>> call, Throwable t) {

                            }
                        });
            }
        });

    }
}